const TextContext = require("./TextContext.js");
const ScriptImport = require("./ScriptImport.js");
module.exports = class ScriptContext {
	textContext = null;
	usefulScriptLine = [];
	/**@type ScriptImport[]*/
	imports = [];
	constructor(scriptPath) {
		this.textContext = new TextContext(scriptPath);
		this.analysis();
	}
	analysis() {
		let importLine;
		for (const line of this.textContext) {
			let formatLine = line
				.replace(/{/g, " { ")
				.replace(/}/g, " } ")
				.replace(/,/g, ", ")
				.replace(/\s+/g, " ")
				.trim();
			//去除注释
			formatLine = this.removeComment(formatLine);
			
			//去除空行
			if (formatLine === "") {
				continue;
			}
			
			this.usefulScriptLine.push(formatLine);
			
			//import同一语句只占一行
			if (importLine) {
				formatLine = importLine + formatLine;
			}
			if (importLine || formatLine.startsWith("import ")) {
				if (this.isLegalImportLine(formatLine)) {
					this.imports.push(new ScriptImport(formatLine));
					importLine = "";
				} else {
					//换行的import语句
					importLine = formatLine;
				}
			}
		}
	}
	removeComment(formatLine) {
		if (
			formatLine.startsWith("//") ||
			formatLine.startsWith("/*") ||
			formatLine.startsWith("*")
		) {
			return "";
		}
		return formatLine.split("//")[0];
	}
	isLegalImportLine(importLine) {
		if (!importLine.startsWith("import ")) {
			return false;
		}
		return !!importLine.match(/["']/g);
		
	}
}
